﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ConfApp.Models;
using Newtonsoft.Json;

namespace ConfApp.Services.Twitter
{
    public class TwitterStore : Store, ITwitterStore
    {
        private const string TwittsStore = "TwittsStore";
        
        private List<Twitt> _twitts;
        private List<string > _twittIds;
        
        public TwitterStore()
        {
            //DeleteStore(TwittsStore);
            Initialize();
        }

        public string SinceId { get; set; }

        public IEnumerable<Twitt> GetTwitts()
        {
            return _twitts.OrderByDescending(t => t.Date);
        }

        public int SaveTwitts(IEnumerable<Twitt> twitts)
        {
            var count = 0;
            foreach (var twitt in twitts)
            {
                if(!_twittIds.Contains(twitt.ID))
                {
                    _twitts.Add(twitt);
                    _twittIds.Add(twitt.ID);
                    count++;
                }
            }
            SaveStore();
            return count;
        }

        public void SaveStore()
        {
            var twittBatch = new TwittBatch()
            {
                MaxId = SinceId,
                Twitts = _twitts.Take(100).OrderByDescending(t=>t.Date).ToList()
            };
            StoreDataToJson(TwittsStore, twittBatch);
        }

        private void Initialize()
        {
            var tweetBatch = GetDataFromJson<TwittBatch>(TwittsStore);
            _twitts = tweetBatch.Twitts;
            _twittIds = _twitts.Select(t => t.ID).ToList();
            SinceId = tweetBatch.MaxId;
        }
    }
}
